<?php

class EventDataInterpreterService extends \app\service\BaseService {

    protected $logpath; 
    private $default_url = '';

    public function __construct() {
        parent::__construct();
        $this->logpath = strtolower(__CLASS__);
        $this->CORE->loader->lib('Curl', FALSE);
    }

    public function execute() {
        $res = $this->fetchAndParseData();
        $res->success || $this->recordObject($res);
        return $res;
    }

    private function fetchAndParseData() {
        try {
            $curl = new Curl;
            $curl->addHeader('Content-Type: application/json; charset=utf-8');
            $errmsg = $curl->httpGet($this->default_url, $response);
            $curl->close();
            if ($response === FALSE) {
                return outputObject(FALSE, '第三方回调数据获取失败：' . $errmsg, NULL, __FUNCTION__, __LINE__);
            }
            return $this->interperterData($response);
        } catch (\Exception $e) {
            return outputObject(FALSE, '获取第三方回调数据时发生未知错误：' . $e->getMessage(), NULL, __FUNCTION__, __LINE__);
        }
    }

    private function interperterData($response) {
        $decodeRes = json_decode(str_replace('\'', "\\'", $response));
        if (!$decodeRes) {
            return outputObject(FALSE, sprintf('第三方回调数据解析失败：%s | %s', json_last_error(), $response), NULL, __FUNCTION__, __LINE__);
        }
        if (!$decodeRes->success) {
            return outputObject(FALSE, sprintf('回调数据请求api发生未知错误：%s | %s', $decodeRes->message, $response), NULL, __FUNCTION__, __LINE__);
        }
        if (!$decodeRes->data || !is_object($decodeRes->data)) {
            return outputObject(FALSE, '解析第三方数据时格式解析失败 | ' . $response, NULL, __FUNCTION__, __LINE__);
        }

        $eventType = isset($decodeRes->data->event_key) ? trim($decodeRes->data->event_key) : '';
        $eventContent = isset($decodeRes->data->post_data) ? $decodeRes->data->post_data : '';
        if (!$eventType || !$eventContent) {
            return outputObject(FALSE, '解析第三方数据时关键信息不合要求 | ' . $response, NULL, __FUNCTION__, __LINE__);
        }
        if (!is_object($eventContent) || !isset($eventContent->strContext)) {
            return outputObject(FALSE, '解析第三方关键信息出错 | ' . $response, NULL, __FILE__, __LINE__);
        }
        $content = json_decode($eventContent->strContext);
        if (!$content) {
            return outputObject(FALSE, sprintf('第三方回调数据解析失败：%s | %s', json_last_error(), $content), NULL, __FUNCTION__, __LINE__);
        }

        return outputObject(TRUE, '第三方回调数据解析成功', ['event_type' => $eventType, 'content' => $content], __FUNCTION__, __LINE__);
    }
}
